package com.cloudeye.logtest.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;

/**
 * Created by lafangyuan on 2021/1/4.
 */
@Slf4j
public class HttpServer {

    public void run() throws InterruptedException {
        ServerBootstrap bootstrap = new ServerBootstrap();
        EventLoopGroup group = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        bootstrap.group(group,worker).channel(NioServerSocketChannel.class)
        .childOption(ChannelOption.SO_KEEPALIVE,true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new HttpServerCodec())
                                .addLast(new HttpContentCompressor())
                                .addLast(new HttpObjectAggregator(66666))
                                .addLast(new HttpServerDemoChannel());
                    }
                });
        ChannelFuture sync = bootstrap.bind(8888).sync();
        sync.channel().closeFuture().sync();
    }

    class HttpServerDemoChannel extends SimpleChannelInboundHandler<FullHttpRequest>{


        @Override
        protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
            String content = String.format("request:url:%s method:%s",req.uri(),req.method());
            log.info(content);
//            Thread.sleep(new Random().nextInt(5000));
            FullHttpResponse response = new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK,
                    Unpooled.wrappedBuffer(content.getBytes())
            );
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        }
    }

    public static void main(String[] args) {
        try {
            new HttpServer().run();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
